package com.mazong.servershiroaa.shiro;

import com.mazong.servershiroaa.mapper.IDbSecurityMapper;
import com.mazong.servershiroaa.pojo.TbUser;
import com.mazong.servershiroaa.service.ShiroService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
public class MyUserRealm extends AuthorizingRealm {

    @Autowired
    private ShiroService shiroService;

    /**
     * 1、用户验证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("doGetAuthenticationInfo,执行用户认证");

        //--1 判断用户名是否存在
        UsernamePasswordToken userinfo = (UsernamePasswordToken) token;
        log.info("doGetAuthenticationInfo,username={}", userinfo.getUsername());
        TbUser user = shiroService.getUserByName(userinfo.getUsername());
        if(null == userinfo) {
            log.info("doGetAuthenticationInfo,不存在用户:{}", userinfo.getUsername());
            return null;
        }

        //--2 判断密码
        log.info("doGetAuthenticationInfo,判断密码:{}", user.getPassword());
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }

    /**
     * 2、用户授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("AuthorizationInfo,执行用户授权");

        //--1 获取用户信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();

        //--2 获取用户权限
        List<String> perms = shiroService.getPermissionsById(user.getId());
        if(perms == null) {
            return info;
        }

        //--3 添加权限
        info.addStringPermissions(perms);

        return info;
    }
}
